<template>
  <div style="updatePhoto">
    <!-- 绑定父组件传入 -->
    <img :src="image" ref="image" class="image" />
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    ></van-nav-bar>
  </div>
</template>

<script>
import { editUserPhoto } from '@/api/user'
// 导人裁切样式库
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
// import { getUserInfo } from '@/api/user'
export default {
  data () {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null // 裁切器实例
    }
  },
  props: {
    // 声明接收父组件传入
    file: {
      // type: Object,
      required: true
    }
  },
  mounted () {
    // 获取需要裁切的图片 DOM
    const image = this.$refs.image
    // 图片裁切的各种属性
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    // console.log(cropper)
  },
  methods: {
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(blob => {
          resolve(blob)
        })
      })
    },
    async onConfirm () {
      this.$toast.loading({
        message: '保存中',
        forbidClick: true,
        duration: 0
      })

      // 因为 getCroppedCanvas 返回了Promise 所以可以用 await
      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', file)
      // 如果要求 Content-Type 是 multipart/form-data,则一定要提交 FormData数据对象，专门用于文件上传的，不能提交{},没用

      // const fd = new FormData()
      // fd.append('photo', this.file)
      await editUserPhoto(fd)

      // 更新父组件中的用户头像
      this.$emit('updatephoto', window.URL.createObjectURL(file))
      // 关闭弹出层
      this.$emit('close')
      this.$toast.success('保存成功')
      this.image = ''
    }
  }
}
</script>

<style lang="less" scoped>
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
.image {
  display: block;
  max-width: 100%;
}
</style>
